import os
import json
from util import send_mqtt_message
from setting import *
from db_method import DataBaseMethod
from util import calculate_md5
from datetime import datetime
import logging

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

class SentryVedioMd5:

    def get_sentry_task(self): # 获取任务

        task = DataBaseMethod().get_upload_video_status_by_calculate_md5_status()

        return task

    def check_vedio_md5(self, row_md5, vedio_path): # 检测视频md5

        # 检测视频是否存在
        if not os.path.exists(vedio_path):

            return False
        
        video_name = os.path.basename(vedio_path)

        md5 = calculate_md5(vedio_path)

        if md5 == row_md5:

            DataBaseMethod().update_upload_video_status({"orderid": video_name, "calculate_md5_status": '验证成功'})

            DataBaseMethod().update_door_task_video_status({"orderid": video_name.replace(".mp4", ''), "video_status": 'md5验证成功'})

            return True
        
        else:

            return False


    def send_video_upload_command(self, cabinet_mac, orderid): # 下发上传视频指令

        topic = "rfid_cabinet/rx/{}".format(cabinet_mac)
        # topic = "rfid_cabinet/rx/620790426a0e"

        message = {
            "task_type": "上传购物视频",
            "task_data": {
                "orderid": orderid
            }
        }

        send_mqtt_message(broker_address=BROKER_ADDRESS, broker_port=BROKER_PORT, topic=topic, message=json.dumps(message))

        DataBaseMethod().update_door_task_video_status({"orderid": orderid, "video_status": "上传任务以下发"})

        logger.info("下发上传视频指令:{}".format(orderid))


    def sentry(self):

        task = DataBaseMethod().get_upload_video_status_by_calculate_md5_status() # 获取待验证的视频

        if task ==None: # 没有待验证的视频则下发上传视频指令

            door_task_info = DataBaseMethod().get_last_door_task_by_video_status_is_null() # 查询没有下发上传视频指令的door_task

            if not door_task_info: # 没有要上传的视频

                logger.info("没有要上传的视频")

                return
            
            orderid = door_task_info["orderid"]
            
            cabinet_info = DataBaseMethod().get_cabinet_info_by_id(door_task_info["cabinet_id"])

            cabinet_mac = cabinet_info['mac']

            self.send_video_upload_command(cabinet_mac=cabinet_mac, orderid=orderid)


            return
        
        else:

            vedio_path="/media/rfid_cabinet/{}".format(task["orderid"])

            logger.info(task["submit_time"])
            logger.info(type(task["submit_time"]))

            # 获取当前时间  
            current_time = datetime.now()  

            # 计算时间差  
            time_difference = current_time - task["submit_time"]  

            # 将时间差转换为秒数  
            seconds_passed = time_difference.total_seconds() 

            if seconds_passed >= 120:

                DataBaseMethod().update_upload_video_status({"orderid": task["orderid"], "calculate_md5_status": '验证失败'})

                DataBaseMethod().update_door_task_video_status({"orderid": task["orderid"].replace(".mp4", ''), "video_status": 'md5验证失败'})

                logger.info("{}: 超时验证失败".format(task["orderid"]))

                return

            # 验证视频
            result = self.check_vedio_md5(row_md5=task["md5"], vedio_path=vedio_path)

            logger.info("{}: MD5验证结果：{}".format(vedio_path, result))

            



if __name__ == "__main__":

    SentryVedioMd5().sentry()

    



